#include "mycustomscene.h"
#include "mazecontroller.h"
#include "mazemodel.h"
#include "mazeview.h"

MazeController::MazeController(QGraphicsScene *scene, QObject *parent)
    : QObject(parent)
    , m_scene(scene)
    , m_model(nullptr)
    , m_view(nullptr)
    , m_clickCnt(0)
{
    slotStartDemo(10, 10);
}

MazeController::~MazeController()
{
    deleteMembers();
}

void MazeController::slotStartDemo(int width, int height)
{
    deleteMembers();
    m_model   = new MazeModel(width, height);
    m_view    = new MazeView(m_model);
    if(m_scene) m_scene->addItem(m_view);
}

void MazeController::deleteMembers()
{
    if(m_view)
    {
        if(m_scene) m_scene->removeItem(m_view);
        delete m_view;
    }
    if(m_model) delete m_model;
}

QPoint MazeController::converMousePos(QPointF pos)
{
    int x = pos.x() * m_model->width()  / m_view->width();
    int y = pos.y() * m_model->height() / m_view->height();
    return {x, y};
}

void MazeController::slotMouseClickPos(QPointF pos)
{
    if(pos.x() >= m_view->width()) return;
    if(pos.y() >= m_view->height()) return;
    m_pathStart = converMousePos(pos);
    if(++m_clickCnt > 1) m_clickCnt = 0;
    m_view->update();
}

void MazeController::slotMouseMovePos(QPointF pos)
{
    if(pos.x() >= m_view->width()) return;
    if(pos.y() >= m_view->height()) return;
    static QPoint prev(-1, -1);
    m_pathStop = converMousePos(pos);
    if(m_clickCnt == 1 and  prev != m_pathStop)
    {
        m_view->showPointStart(m_pathStart);
        m_view->showPointStop(m_pathStop);
        prev = m_pathStop;
        m_model->findPath(m_pathStart, m_pathStop);
        m_view->update();
    }
}
